package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.service.BusinessService;
import com.neusoft.elmboot.service.BusinessWalletService;
import com.neusoft.elmboot.service.FoodService;
import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家管理端控制器
 */
@RestController
@RequestMapping("/elm/BusinessManagementController")
public class BusinessManagementController {

    @Autowired
    private BusinessService businessService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private BusinessWalletService businessWalletService;

    /**
     * 商家登录
     */
    @PostMapping("/login")
    public ResultBody businessLogin(@RequestParam String businessId,
                                   @RequestParam String password) throws Exception {
        try {
            // 验证商家是否存在
            Business business = businessService.getBusinessById(businessId);
            if (business == null) {
                return ResultBody.error("商家不存在", null);
            }

            // 简单密码验证（实际项目中应该使用加密密码）
            // 这里假设默认密码是 "123456"
            if (!"123456".equals(password)) {
                return ResultBody.error("密码错误", null);
            }

            // 返回商家信息
            Map<String, Object> result = new HashMap<>();
            result.put("businessId", business.getBusinessId());
            result.put("businessName", business.getBusinessName());
            result.put("businessAddress", business.getBusinessAddress());
            result.put("token", "business_token_" + System.currentTimeMillis());

            return ResultBody.success("登录成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("登录失败：" + e.getMessage(), null);
        }
    }

    /**
     * 获取商家基本信息
     */
    @PostMapping("/getBusinessInfo")
    public ResultBody getBusinessInfo(@RequestParam String businessId) throws Exception {
        try {
            Business business = businessService.getBusinessById(businessId);
            if (business == null) {
                return ResultBody.error("商家不存在", null);
            }
            return ResultBody.success("获取成功", business);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("获取商家信息失败", null);
        }
    }

    /**
     * 更新商家信息
     */
    @PostMapping("/updateBusinessInfo")
    public ResultBody updateBusinessInfo(@RequestParam String businessId,
                                        @RequestParam String businessName,
                                        @RequestParam String businessAddress,
                                        @RequestParam String businessExplain,
                                        @RequestParam Double starPrice,
                                        @RequestParam Double deliveryPrice) throws Exception {
        try {
            Business business = businessService.getBusinessById(businessId);
            if (business == null) {
                return ResultBody.error("商家不存在", null);
            }

            business.setBusinessName(businessName);
            business.setBusinessAddress(businessAddress);
            business.setBusinessExplain(businessExplain);
            business.setStarPrice(starPrice);
            business.setDeliveryPrice(deliveryPrice);

            // 使用新的完整更新方法
            businessService.updateBusinessInfo(business);
            
            // 返回更新后的商家信息
            Business updatedBusiness = businessService.getBusinessById(businessId);
            return ResultBody.success("更新成功", updatedBusiness);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("更新商家信息失败", null);
        }
    }

    /**
     * 获取商家菜品列表
     */
    @PostMapping("/getFoodList")
    public ResultBody getFoodList(@RequestParam String businessId) throws Exception {
        try {
            List<Food> foods = foodService.listFoodByBusinessId(businessId);
            return ResultBody.success("获取成功", foods);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("获取菜品列表失败", null);
        }
    }

    /**
     * 添加菜品
     */
    @PostMapping("/addFood")
    public ResultBody addFood(@RequestParam String businessId,
                             @RequestParam String foodName,
                             @RequestParam String foodExplain,
                             @RequestParam Double foodPrice,
                             @RequestParam(required = false) String foodImg) throws Exception {
        try {
            Food food = new Food();
            food.setBusinessId(businessId);
            food.setFoodName(foodName);
            food.setFoodExplain(foodExplain);
            food.setFoodPrice(foodPrice);
            food.setFoodImg(foodImg != null ? foodImg : "default_food.jpg");
            food.setFoodStatus(1); // 默认上架状态

            foodService.addFoodByBusinessId(food);
            return ResultBody.success("添加成功", food);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("添加菜品失败", null);
        }
    }

    /**
     * 更新菜品
     */
    @PostMapping("/updateFood")
    public ResultBody updateFood(@RequestParam Integer foodId,
                                @RequestParam String foodName,
                                @RequestParam String foodExplain,
                                @RequestParam Double foodPrice) throws Exception {
        try {
            Food food = foodService.getFoodById(foodId);
            if (food == null) {
                return ResultBody.error("菜品不存在", null);
            }

            food.setFoodName(foodName);
            food.setFoodExplain(foodExplain);
            food.setFoodPrice(foodPrice);

            foodService.updateFoodById(food);
            return ResultBody.success("更新成功", food);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("更新菜品失败", null);
        }
    }

    /**
     * 删除菜品
     */
    @PostMapping("/deleteFood")
    public ResultBody deleteFood(@RequestParam Integer foodId) throws Exception {
        try {
            foodService.delFoodById(foodId);
            return ResultBody.success("删除成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("删除菜品失败", null);
        }
    }

    /**
     * 获取商家订单列表
     */
    @PostMapping("/getOrderList")
    public ResultBody getOrderList(@RequestParam String businessId) throws Exception {
        try {
            List<Orders> orders = ordersService.listOrdersByBusinessId(businessId);
            return ResultBody.success("获取成功", orders);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("获取订单列表失败", null);
        }
    }

    /**
     * 获取商家仪表板统计数据
     */
    @PostMapping("/getDashboardStats")
    public ResultBody getDashboardStats(@RequestParam String businessId) throws Exception {
        try {
            Map<String, Object> stats = new HashMap<>();

            // 获取今日真实订单统计
            Map<String, Object> todayOrderStats = ordersService.getTodayOrderStats(businessId);
            stats.put("todayOrders", todayOrderStats.getOrDefault("orderCount", 0));
            stats.put("todayRevenue", todayOrderStats.getOrDefault("totalRevenue", "0.00"));

            // 获取菜品数量
            List<Food> foods = foodService.listFoodByBusinessId(businessId);
            stats.put("foodCount", foods.size());

            // 获取商家信息
            Business business = businessService.getBusinessById(businessId);
            stats.put("businessName", business != null ? business.getBusinessName() : "未知商家");

            // 获取钱包余额
            try {
                var walletInfo = businessWalletService.getBusinessWalletInfo(businessId);
                stats.put("walletBalance", walletInfo.getWalletBalance());
            } catch (Exception e) {
                stats.put("walletBalance", "0.00");
            }

            // 模拟评分（实际项目中应该从评价系统获取）
            stats.put("rating", 4.8);

            return ResultBody.success("获取成功", stats);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("获取统计数据失败", null);
        }
    }

    /**
     * 获取商家月度统计数据
     */
    @PostMapping("/getMonthlyStats")
    public ResultBody getMonthlyStats(@RequestParam String businessId) throws Exception {
        try {
            Map<String, Object> stats = new HashMap<>();

            // 获取真实月度订单统计
            Map<String, Object> monthlyOrderStats = ordersService.getMonthlyOrderStats(businessId);
            stats.put("monthlyOrders", monthlyOrderStats.getOrDefault("orderCount", 0));
            stats.put("monthlyRevenue", monthlyOrderStats.getOrDefault("totalRevenue", "0.00"));
            stats.put("avgOrderValue", monthlyOrderStats.getOrDefault("avgOrderValue", "0.00"));
            
            // 模拟其他数据（实际项目中应该从相应表查询）
            Integer orderCount = (Integer) monthlyOrderStats.getOrDefault("orderCount", 0);
            stats.put("customerCount", Math.max(1, orderCount * 2 / 3)); // 估算客户数
            stats.put("repeatCustomers", Math.max(0, orderCount / 5)); // 估算回头客
            stats.put("satisfaction", 92); // 模拟满意度

            return ResultBody.success("获取成功", stats);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("获取月度统计失败", null);
        }
    }

    /**
     * 切换菜品状态（上架/下架）
     */
    @PostMapping("/toggleFoodStatus")
    public ResultBody toggleFoodStatus(@RequestParam Integer foodId) throws Exception {
        try {
            Food food = foodService.getFoodById(foodId);
            if (food == null) {
                return ResultBody.error("菜品不存在", null);
            }
            
            // 切换状态：1变0，0变1
            int newStatus = (food.getFoodStatus() != null && food.getFoodStatus() == 1) ? 0 : 1;
            food.setFoodStatus(newStatus);
            
            foodService.updateFoodById(food);
            return ResultBody.success("状态更新成功", food);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("更新菜品状态失败", null);
        }
    }

    /**
     * 更新订单状态
     */
    @PostMapping("/updateOrderStatus")
    public ResultBody updateOrderStatus(@RequestParam Integer orderId,
                                       @RequestParam Integer status) throws Exception {
        try {
            ordersService.updateOrderState(status, orderId);
            return ResultBody.success("状态更新成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("更新订单状态失败", null);
        }
    }

    /**
     * 商家同意退款
     */
    @PostMapping("/approveRefund")
    public ResultBody approveRefund(@RequestParam Integer orderId) throws Exception {
        try {
            Orders orders = ordersService.getOrdersById(orderId);
            if (orders == null) {
                return ResultBody.error("订单不存在", null);
            }
            // 仅在有退款申请时处理
            if (orders.getRefundStatus() == null || orders.getRefundStatus() != 1) {
                return ResultBody.error("该订单当前没有待处理的退款申请", null);
            }

            Double refundAmount = orders.getFinalTotal() != null ? orders.getFinalTotal() : orders.getOrderTotal();
            if (refundAmount == null || refundAmount <= 0) {
                return ResultBody.error("退款金额异常", null);
            }

            String paymentType = orders.getPaymentType();
            String userId = orders.getUserId();
            String businessId = orders.getBusinessId();

            // 仅钱包支付执行真实资金退款，其它支付方式暂时只记录状态
            if ("wallet".equalsIgnoreCase(paymentType)) {
                businessWalletService.processOrderRefund(userId, businessId, orderId,
                        java.math.BigDecimal.valueOf(refundAmount));
            }

            // 标记订单为已退款：orderState=4（前端基于 refundStatus 决定显示“已退款”还是“已取消”）
            ordersService.updateOrderState(4, orderId);
            ordersService.updateRefundInfo(orderId, 2, orders.getRefundReason());

            return ResultBody.success("已同意退款并处理完成", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("同意退款失败：" + e.getMessage(), null);
        }
    }

    /**
     * 商家拒绝退款
     */
    @PostMapping("/rejectRefund")
    public ResultBody rejectRefund(@RequestParam Integer orderId,
                                 @RequestParam(required = false) String reason) throws Exception {
        try {
            Orders orders = ordersService.getOrdersById(orderId);
            if (orders == null) {
                return ResultBody.error("订单不存在", null);
            }
            if (orders.getRefundStatus() == null || orders.getRefundStatus() != 1) {
                return ResultBody.error("该订单当前没有待处理的退款申请", null);
            }

            // 拒绝退款，不改变支付状态，仅更新退款状态和原因
            String finalReason = reason != null && !reason.isEmpty() ? reason : orders.getRefundReason();
            ordersService.updateRefundInfo(orderId, 3, finalReason);

            return ResultBody.success("已拒绝退款申请", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error("拒绝退款失败：" + e.getMessage(), null);
        }
    }
}
